import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
  getGigaSkuAndProductId,
  getProductPrice,
  getProductTotalPrice,
  gotoGigaProductPage,
} from '@/lib/giga';
import { cn, generateRandomId, getOperationResultColor } from '@/lib/utils';
import {
  ColumnDef,
  ColumnPinningState,
  flexRender,
  getCoreRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  PaginationState,
  SortingState,
  useReactTable,
} from '@tanstack/react-table';
import { ArrowUpDown, Check, ChevronsUpDown, Link, Search } from 'lucide-react';

import { getActivityList, getTemuUserInfo } from '@/api/temu';
import TablePagination from '@/components/TablePagination';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import config, { PostMessageType, SendCorssOriginDataMessage } from '@/config';
import {
  getTemuTotalProductByMallId,
  getTotalActivityProductInfoList,
  regidtrationProductActivity,
} from '@/lib/temu';
import { useTemuNotPersisRegidtrationActivityStore } from '@/store/useTemuNotPersistRegidtrationActivityStore';
import { memo, useDeferredValue, useId } from 'react';
import { toast } from 'sonner';
import useLocalStorage from '../hook/useLocalStorage';
import { RegidtrationActivityOperation } from './RegidtrationActivityOperation';
import { useFilterTable } from './hook/useFilterTable';
import { useSaveTableData } from './hook/useSaveTableData';

export interface RegidtrationActivityTableDataItem {
  skuInfo: string;
  productId: number;
  temuStock: number;
  temuPrice: number;
  gigaPrice: number;
  gigaAvaliable: number;

  // 活动利润
  activityMargin: number;

  // 活动毛利率
  activityRateOfMargin: number;

  // 活动建议价格,单位美分
  suggestActivityPrice: number;
  // 活动建议库存
  suggestActivityStock: number;
  // 最终上报价格
  finalActivityPrice: number;
  // 最终上报库存
  finalActivityStock: number;
  skcId: number;
  skcInfo: string;
  skuId: number;
  mallId: number;
  timeStamp: number;
  opeartionResult: string;
  sessionIds: number[];
  // 所报的活动的标识
  activityIdentify: string;
}

export interface malInfo {
  mallId: number;
  mallName: string;
}

export interface SiteInfo {
  siteName: string;
  siteId: number;
}

export interface LocalStoredValue {
  mallId: number;
  siteId: number;
  status: number;
  fetchPageSize: number;
  regidtrationActivityCondition: {
    // 最少货盘库存数
    minAndEqualGigaAvaliable: number;
    // 毛利率 %((活动参考价格 - giga 产品价格) / (giga 产品价格))
    minAndEqualRateOfMargin: number;
    maxAndEqualRateOfMargin: number;
    // 最少上报库存
    minRegidtratioAvaliable: number;
  };
}

export interface SkcTopStatus {
  label: string;
  status: number;
}

const siteList: SiteInfo[] = [
  {
    siteName: '美国站',
    siteId: 100,
  },
  {
    siteName: '欧洲站',
    siteId: 101,
  },
  {
    siteName: '其他站',
    siteId: 102,
  },
];

// 在售信息
const skcTopStatusList: SkcTopStatus[] = [
  {
    label: '全部',
    status: 1000,
  },
  {
    label: '在售中',
    status: 100,
  },
  {
    label: '未发布到站点',
    status: 0,
  },
  {
    label: '已下架/已终止',
    status: 200,
  },
];

export interface Activity {
  id: string;
  activityType: number;
  activityName: string;
  activityContent: string;
  activityLabelList?: Array<{
    value: string;
    key: number;
  }>;
  activityThematicContent?: string;
  activityThematicName?: string;
  activityThematicId?: number;
  isThematic: boolean;
}

// 生成活动文本
function ActivityText({ activity }: { activity: Activity | undefined }) {
  if (!activity) {
    return <div>未选择活动</div>;
  }
  // console.log(activity);
  if (activity.isThematic) {
    return (
      <div className="flex items-center">
        <div className="flex items-center">
          <span className="whitespace-nowrap">
            [{activity.activityName}]-{activity.activityThematicName}{' '}
          </span>
          {activity.activityLabelList?.map((activityLabel) => {
            if (activityLabel.value === 'Deals额外享') {
              return (
                <span
                  key={activityLabel.key}
                  style={{
                    lineHeight: 1,
                  }}
                >
                  <img
                    src="https://bstatic.kwcdn.com/static/temu-sc-activity/ec05da1e1159e6b5f5d6.png"
                    alt=""
                    width="85"
                    height="14"
                  />
                </span>
              );
            } else {
              return (
                <div key={activityLabel.key} className="act-label-tag_smallActTag__jYdd5">
                  New
                </div>
              );
            }
          })}
        </div>
      </div>
    );
  } else {
    return (
      <div>
        [{activity.activityName}]-{activity.activityContent}
      </div>
    );
  }
}

// 导航到活动中
function goToActivityPage(activity: Activity) {
  if (activity.isThematic) {
    window.open(
      `https://agentseller.temu.com/activity/marketing-activity/detail-new?type=${activity.activityType}&thematicId=${activity.activityThematicId}`,
    );
  } else {
    window.open(
      `https://agentseller.temu.com/activity/marketing-activity/detail-new?type=${activity.activityType}`,
    );
  }
}

// 创建活动的标识,不能使用 selectedActivityId 来创建活动标识,因为 selectedActivityId 是每次渲染都不不同的
function generateActivityIdentify(activity: Activity) {
  return `${activity.activityType}-${activity.activityThematicId || ''}`;
}

// 创建活动的可看的文本内容
function generateActivityText(activity: Activity) {
  let content = '';
  if (activity.isThematic) {
    content = `[${activity.activityName}]-${activity.activityThematicName}`;
  } else {
    content = `[${activity.activityName}]-${activity.activityContent}`;
  }
  return content;
}

function generateMallTableDataKey(storedValue: LocalStoredValue, activity: Activity) {
  return `${storedValue.mallId}-${storedValue.siteId}-${storedValue.status}-${generateActivityIdentify(activity)}`;
}

export default function RegidtrationActivity({
  className,
  ...props
}: {
  className: string;
} & React.HTMLAttributes<HTMLDivElement>) {
  const [tableData, setTableData] = useState<RegidtrationActivityTableDataItem[]>([]);
  const [preprocessTableData, setPreprocessTableData] = useState<
    RegidtrationActivityTableDataItem[]
  >([]);
  const dispatch = useTemuNotPersisRegidtrationActivityStore((state) => state.dispatch);
  const [currentTotal, setCurrentTotal] = useState(0);
  const localStorageKey = config.temu.temuRegidtrationActivityKey;
  const [isRunning, setIsRunning] = useState(false);
  const [selectedActivityId, setSelectedActivityId] = useState('');
  const [activityList, setActivityList] = useState<Activity[]>([]);
  const [openSelecteActivity, setOpenSelecteActivity] = useState(false);
  const { filterString, setFilterString, filteredTableDate } =
    useFilterTable<RegidtrationActivityTableDataItem>(tableData, [
      'skuInfo',
      'productId',
      'skcId',
      'skuId',
      'opeartionResult',
    ]);

  const deferredTableData = useDeferredValue(filteredTableDate);

  const id = useId();
  const [storedValue, setStoredValue] = useLocalStorage<LocalStoredValue>(localStorageKey, {
    mallId: 0,
    siteId: 100,
    status: 100,
    fetchPageSize: 200,
    regidtrationActivityCondition: {
      minAndEqualGigaAvaliable: 10,
      minAndEqualRateOfMargin: 20,
      maxAndEqualRateOfMargin: 100,
      minRegidtratioAvaliable: 15,
    },
  });
  const [malInfoList, setMalInfoList] = useState<malInfo[]>([]);

  const { saveMallTableData, getMallTableData, persistedMallTableData, clearMallTableData } =
    useSaveTableData<RegidtrationActivityTableDataItem>({
      storageKey: config.temu.temuRegidtrationActivityMallTableData,
    });

  // 当店铺切换时修改 tableData
  useEffect(() => {
    const activity = activityList.find((activity) => activity.id === selectedActivityId);
    if (activity) {
      const tableData = getMallTableData(generateMallTableDataKey(storedValue, activity));
      if (tableData) {
        setTableData(tableData);
        setCurrentTotal(tableData.length);
        setPreprocessTableData(tableData);
      } else {
        setTableData([]);
        setCurrentTotal(0);
        setPreprocessTableData([]);
      }
    }
    // console.log('tableData', mallTableData);
  }, [storedValue, activityList, selectedActivityId]);

  // 获取店铺列表信息
  useEffect(() => {
    async function getMallInfoList() {
      try {
        const result = await getTemuUserInfo();
        if (result.success) {
          const { companyList } = result.result;
          const malInfoList = companyList.flatMap((item) => item.malInfoList);
          // console.log(malInfoList);
          setMalInfoList(malInfoList);
          if (malInfoList.length > 0) {
            setStoredValue((prev) => {
              return {
                ...prev,
                mallId: malInfoList[0].mallId,
              };
            });
          }
        } else {
          throw new Error(result.errorMsg || '');
        }
      } catch (error) {
        // console.log(error)
        toast.error(`获取店铺列表失败: ${(error as Error).message}`);
      }
    }
    getMallInfoList();
  }, []);

  // 获取活动列表信息
  useEffect(() => {
    async function getTemuActivityList() {
      try {
        if (!storedValue.mallId) {
          toast.error(`请选择对应的店铺`);
          return;
        }
        const result = await getActivityList({
          mallId: storedValue.mallId,
        });
        if (result.success) {
          const { activityList } = result.result;
          const newActivityList: Activity[] = [];
          activityList.forEach((item) => {
            const { thematicList } = item;
            if (thematicList.length > 0) {
              thematicList.forEach((thematic) => {
                newActivityList.push({
                  id: generateRandomId(),
                  activityType: item.activityType,
                  activityName: item.activityName,
                  activityContent: item.activityContent,
                  isThematic: true,
                  activityLabelList: thematic.activityLabelList,
                  activityThematicContent: thematic.activityThematicContent,
                  activityThematicName: thematic.activityThematicName,
                  activityThematicId: thematic.activityThematicId,
                });
              });
            } else {
              newActivityList.push({
                id: generateRandomId(),
                activityType: item.activityType,
                activityName: item.activityName,
                activityContent: item.activityContent,
                isThematic: false,
              });
            }
          });

          setActivityList(newActivityList);
        } else {
          throw new Error(result.errorMsg || '');
        }
      } catch (error) {
        // console.log(error)
        toast.error(`获取活动列表失败(请确保登录到对应的授权站点): ${(error as Error).message}`);
      }
    }
    getTemuActivityList();
  }, [storedValue.mallId]);

  const updateTableData = useCallback(
    (tableDataItem: RegidtrationActivityTableDataItem, activity: Activity) => {
      tableDataItem.timeStamp = Date.now();
      // 如果 productId 已经存在于 tableData 中,那么就更新它,否则就添加一个新的
      setTableData((prev) => {
        const index = prev.findIndex((item) => item.productId === tableDataItem.productId);
        let newTableData = [];
        if (index === -1) {
          newTableData = [...prev, tableDataItem];
        } else {
          // console.log('更新表格数据', tableDataItem);
          newTableData = [...prev.slice(0, index), tableDataItem, ...prev.slice(index + 1)];
        }
        saveMallTableData(generateMallTableDataKey(storedValue, activity), newTableData);
        return newTableData;
      });
    },
    [storedValue],
  );

  // 运行任务
  const runTask = useCallback(
    async (tableDataItem: RegidtrationActivityTableDataItem) => {
      const {
        skuInfo,
        temuStock,
        temuPrice,
        skcId,
        skcInfo,
        skuId,
        mallId,
        productId,
        sessionIds,
        suggestActivityPrice,
        suggestActivityStock,
        activityIdentify,
      } = tableDataItem;
      const regidtrationActivityCondition = storedValue.regidtrationActivityCondition;
      const minAndEqualGigaAvaliable = regidtrationActivityCondition.minAndEqualGigaAvaliable;
      const minAndEqualRateOfMargin = regidtrationActivityCondition.minAndEqualRateOfMargin;
      const maxAndEqualRateOfMargin = regidtrationActivityCondition.maxAndEqualRateOfMargin;
      const minRegidtratioAvaliable = regidtrationActivityCondition.minRegidtratioAvaliable;

      const activity = activityList.find(
        (item) => generateActivityIdentify(item) === activityIdentify,
      );
      if (!activity) {
        throw new Error('找不到对应的活动');
      }

      if (!skuInfo || Number.isNaN(temuStock) || Number.isNaN(temuPrice)) {
        const message = `无法获取到 temu 产品的 sku 信息`;
        tableDataItem.opeartionResult = `失败(${message})`;
        updateTableData(tableDataItem, activity);
        toast.error(`${productId} ${message}`, {
          position: 'top-right',
        });
        throw new Error(`${productId} ${message}`);
      }

      if (!suggestActivityPrice || !suggestActivityStock || sessionIds.length === 0) {
        const message = `无法获取到 temu 产品的活动建议信息`;
        tableDataItem.opeartionResult = `不符合条件(${message})`;
        updateTableData(tableDataItem, activity);
        return;
        // toast.error(`${productId} ${message}`, {
        //   position: 'top-right',
        // });
        // throw new Error(`${productId} ${message}`);
      }

      // 开始获取货盘的信息
      const [gigaSku, gigaProductId] = getGigaSkuAndProductId(skuInfo);
      let gigaAvaliable = 0;
      // giga 商品价格,单位是美分,如果不能获取返回 0
      let gigaPrice = 0;
      try {
        const result = await getProductPrice(gigaProductId);
        if (result.code === 200) {
          if (!result.data.qty_visible) {
            throw new Error(`请先登录 giga 网站`);
          }
          gigaAvaliable = result.data?.quantity?.quantity || 0;
          gigaPrice = getProductTotalPrice(result);
          if (gigaPrice === 0 || gigaPrice === config.NotFoundBaseGigaProductPrice * 100) {
            // throw new Error(`giga 商品价格为 0,请检查商品是否存在`);
            // 如果价格为 0,表明商品是不可用的,这个时候把库存设置为 0
            gigaAvaliable = 0;
          }
        } else {
          throw new Error(`${result && result.msg}`);
        }
      } catch (error) {
        toast.error(`${skuInfo} 获取 giga 库存和价格失败: ${(error as Error).message}`, {
          position: 'top-right',
        });
        tableDataItem.opeartionResult = '失败(获取 giga 库存和价格失败)';
        updateTableData(tableDataItem, activity);
        throw error;
      }
      tableDataItem.gigaPrice = gigaPrice;
      tableDataItem.gigaAvaliable = gigaAvaliable;

      // 如果价格为 0,那么库存也会被调为 0,可以保证后续的操作中 gigaPrice 不为 0
      if (gigaAvaliable < minAndEqualGigaAvaliable) {
        tableDataItem.opeartionResult = `不符合条件(因库存数量${gigaAvaliable}不足不参与报名活动)`;
        updateTableData(tableDataItem, activity);
        return;
      }

      // 计算初始的活动毛利率
      const initActivityRateOfMargin = ((suggestActivityPrice - gigaPrice) / gigaPrice) * 100;

      if (initActivityRateOfMargin < minAndEqualRateOfMargin) {
        tableDataItem.opeartionResult = `不符合条件(因毛利率${initActivityRateOfMargin.toFixed(2)}%太低不参与报名活动)`;
        updateTableData(tableDataItem, activity);
        return;
      }

      let finalActivityStock = suggestActivityStock;
      if (suggestActivityStock < minRegidtratioAvaliable) {
        finalActivityStock = minRegidtratioAvaliable;
      }

      let finalActivityPrice = suggestActivityPrice;
      if (initActivityRateOfMargin > maxAndEqualRateOfMargin) {
        finalActivityPrice = (maxAndEqualRateOfMargin * gigaPrice) / 100 + gigaPrice;
      }

      try {
        // console.log(activity);
        const { successMessage } = await regidtrationProductActivity({
          activityType: activity.activityType,
          activityThematicId: activity.activityThematicId,
          productId,
          activityStock: finalActivityStock,
          mallId,
          siteId: storedValue.siteId,
          skcId,
          skuId,
          activityPrice: finalActivityPrice,
          sessionIds,
        });
        tableDataItem.opeartionResult = `成功(${successMessage})`;
        tableDataItem.finalActivityStock = finalActivityStock;
        tableDataItem.finalActivityPrice = finalActivityPrice;
        tableDataItem.activityMargin = finalActivityPrice - gigaPrice;
        tableDataItem.activityRateOfMargin = ((finalActivityPrice - gigaPrice) / gigaPrice) * 100;
        updateTableData(tableDataItem, activity);
        return;
      } catch (error) {
        toast.error(`${productId} 报名活动失败: ${(error as Error).message}`, {
          position: 'top-right',
        });
        tableDataItem.opeartionResult = `失败(${(error as Error).message})`;
        updateTableData(tableDataItem, activity);
        throw error;
      }
    },
    [updateTableData, storedValue, activityList],
  );

  // 批量运行任务
  const runBatchTask = useCallback(
    async (preprocessTableData: RegidtrationActivityTableDataItem[], isEnterQueue = true) => {
      await Promise.all(
        preprocessTableData.map((preprocessTableDataItem) => {
          if (isEnterQueue) {
            return new Promise((resolve, reject) => {
              dispatch({
                type: 'enqueueTask',
                resolve,
                reject,
                task: {
                  handleTask: async () => {
                    await runTask(preprocessTableDataItem);
                  },
                  taskInfo: {
                    id: preprocessTableDataItem.productId,
                    ...preprocessTableDataItem,
                  },
                },
              });
            });
          } else {
            return runTask(preprocessTableDataItem);
          }
        }),
      );
    },
    [runTask],
  );

  async function fetchAndRegidtrationActivity({ activity }: { activity?: Activity } = {}) {
    const preprocessTableData = await fetchTemuProductAndActivityInfo({
      isSavePreprocessTableData: false,
      activity,
    });
    await runBatchTask(preprocessTableData);
  }

  // 一键报名活动
  async function batchFetchAndRegidtrationActivity() {
    const selectedActivityIndex = activityList.findIndex((item) => item.id === selectedActivityId);
    const selectedActivity = activityList[selectedActivityIndex];
    if (!selectedActivity) {
      throw new Error('请先选择起始活动');
    }
    for (let i = selectedActivityIndex; i < activityList.length; i++) {
      const activity = activityList[i];
      setSelectedActivityId(activity.id);
      // 开始进行报名
      try {
        await fetchAndRegidtrationActivity({
          activity,
        });
        persistedMallTableData();
        // 清理任务队列,这样任务可以继续执行
        dispatch({
          type: 'clearAllQueue',
        });

        toast.success(`${generateActivityText(activity)} 报名活动成功`);
      } catch (error) {
        throw new Error(
          `${generateActivityText(activity)} 报名活动失败: ${(error as Error).message}`,
        );
      }
    }
  }

  // 获取 temu 商品信息和活动报价信息
  async function fetchTemuProductAndActivityInfo({
    isSavePreprocessTableData,
    activity,
  }: {
    isSavePreprocessTableData: boolean;
    activity?: Activity;
  }) {
    if (!activity) {
      activity = activityList.find((item) => item.id === selectedActivityId);
    }
    if (!activity) {
      throw new Error('未选择活动');
    }

    setIsRunning(true);
    setTableData([]);
    setCurrentTotal(0);
    const pageSize = storedValue.fetchPageSize || 200;

    // 获取所有的 temu 产品信息
    const [temuTotalProduct, temuTotalActivityProductInfoList] = await Promise.all([
      getTemuTotalProductByMallId({
        mallId: storedValue.mallId,
        pageSize,
        status: storedValue.status,
        obtainedTotalPageSize: (totalSize) => {
          setCurrentTotal(totalSize);
        },
      }),
      getTotalActivityProductInfoList({
        activityType: activity.activityType,
        activityThematicId: activity.activityThematicId,
        mallId: storedValue.mallId,
      }),
    ]);
    setIsRunning(false);

    const preprocessTableData = temuTotalProduct.map((temuProduct) => {
      const { skuInfo, temuStock, temuPrice, productId, skcId, skcInfo, skuId } = temuProduct;
      const activityProductInfoList = temuTotalActivityProductInfoList.find(
        (item) => item.productId === productId,
      );
      return {
        skuInfo: skuInfo,
        productId: productId,
        temuStock,
        temuPrice,
        gigaPrice: NaN,
        gigaAvaliable: NaN,
        activityMargin: NaN,
        activityRateOfMargin: NaN,
        // 代填
        suggestActivityPrice: activityProductInfoList?.suggestActivityPrice || NaN,
        // 代填
        suggestActivityStock: activityProductInfoList?.suggestActivityStock || NaN,
        sessionIds: activityProductInfoList?.sessionIds || [],
        finalActivityPrice: NaN,
        finalActivityStock: NaN,
        skcId: skcId,
        skcInfo: skcInfo,
        skuId: skuId,
        mallId: storedValue.mallId || NaN,
        timeStamp: Date.now(),
        opeartionResult: '还未报名活动',
        activityIdentify: generateActivityIdentify(activity),
      };
    });
    setTableData(preprocessTableData);
    saveMallTableData(generateMallTableDataKey(storedValue, activity), preprocessTableData);

    // console.log(preprocessTableData);
    // 如果是有后续的上报活动,那么不用设置预配置信息
    if (!isSavePreprocessTableData) {
      return preprocessTableData;
    }
    setPreprocessTableData(preprocessTableData);
    return preprocessTableData;
  }

  async function regidtrationActivity() {
    await runBatchTask(preprocessTableData);
  }

  async function clearTableData() {
    setTableData([]);
    setPreprocessTableData([]);
    const activity = activityList.find((item) => item.id === selectedActivityId);
    if (activity) {
      saveMallTableData(generateMallTableDataKey(storedValue, activity), []);
    }
  }

  return (
    <div {...props} className={cn(className, 'flex flex-col')}>
      <div className="flex items-center">
        <div className="flex gap-2 items-center mr-3">
          <Label className="whitespace-nowrap mb-0" htmlFor={id + 'mall-info-list'}>
            店铺账号:
          </Label>
          <Select
            value={storedValue.mallId + ''}
            onValueChange={(value) => {
              // console.log(value);
              setStoredValue((prev) => {
                return {
                  ...prev,
                  mallId: +value,
                };
              });
            }}
          >
            <SelectTrigger id={id + 'mall-info-list'} className="w-[120px]">
              <SelectValue placeholder="---- 请选择店铺 ----" />
            </SelectTrigger>
            <SelectContent
              style={{
                zIndex: config.SelectZindex,
              }}
            >
              <SelectGroup>
                {malInfoList.map(({ mallId, mallName }) => {
                  return (
                    <SelectItem key={mallId} value={mallId + ''}>
                      {mallName}
                    </SelectItem>
                  );
                })}
              </SelectGroup>
            </SelectContent>
          </Select>
        </div>
        <div className="flex gap-2 items-center mr-3">
          <Label className="whitespace-nowrap mb-0" htmlFor={id + 'site-info-list'}>
            站点:
          </Label>
          <Select
            value={storedValue.siteId + ''}
            onValueChange={(value) => {
              // console.log(value);
              setStoredValue((prev) => {
                return {
                  ...prev,
                  siteId: +value,
                };
              });
            }}
          >
            <SelectTrigger id={id + 'site-info-list'} className="w-[120px]">
              <SelectValue placeholder="---- 请选择站点 ----" />
            </SelectTrigger>
            <SelectContent
              style={{
                zIndex: config.SelectZindex,
              }}
            >
              <SelectGroup>
                {siteList.map(({ siteId, siteName }) => {
                  return (
                    <SelectItem key={siteId} value={siteId + ''}>
                      {siteName}
                    </SelectItem>
                  );
                })}
              </SelectGroup>
            </SelectContent>
          </Select>
        </div>
        <div className="flex gap-2 items-center">
          <Label className="whitespace-nowrap mb-0" htmlFor={id + '-status'}>
            产品状态:
          </Label>
          <Select
            value={storedValue.status + ''}
            onValueChange={(value) => {
              // console.log(value);
              setStoredValue((prev) => {
                return {
                  ...prev,
                  status: +value,
                };
              });
            }}
          >
            <SelectTrigger id={id + '-status'} className="w-[120px]">
              <SelectValue placeholder="---- 请选择产品状态 ----" />
            </SelectTrigger>
            <SelectContent
              style={{
                zIndex: config.SelectZindex,
              }}
            >
              <SelectGroup>
                {skcTopStatusList.map(({ label, status }) => {
                  return (
                    <SelectItem key={status} value={status + ''}>
                      {label}
                    </SelectItem>
                  );
                })}
              </SelectGroup>
            </SelectContent>
          </Select>
        </div>
        <div className="flex px-3 gap-2 items-center py-4">
          <Label className="whitespace-nowrap" htmlFor={id + '-fetch-page-size'}>
            一次拉取商品数量:
          </Label>
          <Input
            type="number"
            value={storedValue.fetchPageSize}
            onChange={(event) => {
              const newFetchPageSize = Number(event.target.value);
              if (newFetchPageSize > 1000 || newFetchPageSize < 1) {
                toast.error('每次拉取商品数量必须在 1 到 1000 之间');
                return;
              }
              setStoredValue((prev) => {
                return {
                  ...prev,
                  fetchPageSize: newFetchPageSize,
                };
              });
            }}
            id={id + '-fetch-page-size'}
            className="h-10 rounded-md border border-input px-3 py-2 w-[120px]"
          />
        </div>
      </div>

      {/* （参考申报价格-大建云仓价格）/大建云仓价格 < 20% 就不参加活动 */}
      {/* （参考申报价格-大建云仓价格）/大建云仓价格>100% 就只取2倍的云仓价格 */}
      <div className="border border-input rounded-lg py-3 pb-0 pl-2 relative mt-1">
        <span className="absolute left-5 top-0 translate-y-[-50%] px-1 text-base bg-white">
          上报活动条件
        </span>
        <div className="flex items-center flex-wrap">
          <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray">
            <Label className="whitespace-nowrap" htmlFor={id + '-min-and-equal-giga-avaliable'}>
              最少 giga 库存数:
            </Label>
            <div className="relative">
              <div className="absolute w-[40px] bg-muted h-full flex items-center">
                <span className="m-auto text-sm">{'≥'}</span>
              </div>
              <Input
                value={storedValue.regidtrationActivityCondition.minAndEqualGigaAvaliable}
                type="number"
                onChange={(event) => {
                  setStoredValue({
                    ...storedValue,
                    regidtrationActivityCondition: {
                      ...storedValue.regidtrationActivityCondition,
                      minAndEqualGigaAvaliable: Number(event.target.value),
                    },
                  });
                }}
                id={id + '-min-and-equal-giga-avaliable'}
                className="h-10 w-32 rounded-md border border-input px-3 py-2 mr-auto pl-[50px]"
              />
            </div>
          </div>
          <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray">
            <Label className="whitespace-nowrap" htmlFor={id + '-min-and-rate-of-margin'}>
              最低毛利率:
            </Label>
            <div className="relative">
              <div className="absolute w-[40px] bg-muted h-full flex items-center">
                <span className="m-auto text-sm">{'≥'}</span>
              </div>
              <Input
                type="number"
                value={storedValue.regidtrationActivityCondition.minAndEqualRateOfMargin}
                onChange={(event) => {
                  setStoredValue({
                    ...storedValue,
                    regidtrationActivityCondition: {
                      ...storedValue.regidtrationActivityCondition,
                      minAndEqualRateOfMargin: Number(event.target.value),
                    },
                  });
                }}
                id={id + '-min-and-rate-of-margin'}
                className="h-10 w-48 rounded-md border border-input px-3 py-2 mr-auto pl-[50px] pr-[50px]"
              />
              <div className="absolute w-[40px] bg-muted h-full flex items-center right-0 top-0">
                <span className="m-auto text-sm">{'%'}</span>
              </div>
            </div>
          </div>

          <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray">
            <Label className="whitespace-nowrap" htmlFor={id + '-max-and-rate-of-margin'}>
              最高毛利率:
            </Label>
            <div className="relative">
              <div className="absolute w-[40px] bg-muted h-full flex items-center">
                <span className="m-auto text-sm">{'≤'}</span>
              </div>
              <Input
                type="number"
                value={storedValue.regidtrationActivityCondition.maxAndEqualRateOfMargin}
                onChange={(event) => {
                  setStoredValue({
                    ...storedValue,
                    regidtrationActivityCondition: {
                      ...storedValue.regidtrationActivityCondition,
                      maxAndEqualRateOfMargin: Number(event.target.value),
                    },
                  });
                }}
                id={id + '-max-and-rate-of-margin'}
                className="h-10 w-48 rounded-md border border-input px-3 py-2 mr-auto pl-[50px] pr-[50px]"
              />
              <div className="absolute w-[40px] bg-muted h-full flex items-center right-0 top-0">
                <span className="m-auto text-sm">{'%'}</span>
              </div>
            </div>
          </div>
          <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray">
            <Label className="whitespace-nowrap" htmlFor={id + '-min-regidtratio-avaliable'}>
              最小上报库存:
            </Label>
            <div className="relative">
              <div className="absolute w-[40px] bg-muted h-full flex items-center">
                <span className="m-auto text-sm">{'≥'}</span>
              </div>
              <Input
                type="number"
                value={storedValue.regidtrationActivityCondition.minRegidtratioAvaliable}
                onChange={(event) => {
                  setStoredValue({
                    ...storedValue,
                    regidtrationActivityCondition: {
                      ...storedValue.regidtrationActivityCondition,
                      minRegidtratioAvaliable: Number(event.target.value),
                    },
                  });
                }}
                id={id + '-min-regidtratio-avaliable'}
                className="h-10 w-32 rounded-md border border-input px-3 py-2 mr-auto pl-[50px]"
              />
            </div>
          </div>
        </div>
      </div>

      {/* 选择报名活动 */}
      <div className="flex items-center mt-2">
        <Popover open={openSelecteActivity} onOpenChange={setOpenSelecteActivity}>
          <PopoverTrigger asChild>
            <Button
              variant="outline"
              role="combobox"
              aria-expanded={openSelecteActivity}
              className="w-[400px] justify-between"
            >
              <div className="w-full overflow-hidden text-left">
                {selectedActivityId ? (
                  <ActivityText
                    activity={activityList.find((item) => item.id === selectedActivityId)}
                  ></ActivityText>
                ) : (
                  <span className="text-gray-600">选择报名的活动</span>
                )}
              </div>
              <ChevronsUpDown className="opacity-50" />
            </Button>
          </PopoverTrigger>
          <PopoverContent
            className="min-w-[600px] p-0"
            style={{
              zIndex: config.alertDialogZIndex,
            }}
          >
            <Command
              filter={(value, search) => {
                const item = activityList.find((item) => item.id === value);
                if (
                  (
                    (item?.activityContent || '') +
                    (item?.activityName || '') +
                    item?.activityThematicContent +
                    item?.activityThematicName
                  ).includes(search)
                ) {
                  return 1;
                } else {
                  return 0;
                }
              }}
            >
              <CommandInput placeholder="搜索对应的活动..." className="h-9" />
              <CommandList>
                <CommandEmpty>没有匹配的活动</CommandEmpty>
                <CommandGroup>
                  {activityList.map((activity) => (
                    <CommandItem
                      key={activity.id}
                      value={activity.id}
                      onSelect={(currentValue) => {
                        setSelectedActivityId(currentValue);
                        setOpenSelecteActivity(false);
                      }}
                    >
                      <ActivityText activity={activity}></ActivityText>
                      <Check
                        className={cn(
                          'ml-auto',
                          selectedActivityId === activity.id ? 'opacity-100' : 'opacity-0',
                        )}
                      />
                    </CommandItem>
                  ))}
                </CommandGroup>
              </CommandList>
            </Command>
          </PopoverContent>
        </Popover>
        <div
          className="ml-3"
          onClick={() => {
            const activity = activityList.find((item) => item.id === selectedActivityId);
            if (activity) {
              goToActivityPage(activity);
            }
          }}
        >
          <Link className="cursor-pointer text-blue-600 mb-[-4px]" size={18}></Link>
        </div>
        <Button
          onClick={async () => {
            try {
              await batchFetchAndRegidtrationActivity();
              // 持久化一下数据
              persistedMallTableData();
              toast.success('一键报名活动任务完成');
            } catch (error) {
              toast.error((error as Error).message);
            }
          }}
          size="sm"
          className="ml-3 primary-color"
        >
          一键报名活动
        </Button>
        <Button
          onClick={async () => {
            window.parent.postMessage(
              {
                type: PostMessageType.exportCorssOriginData,
                data: {
                  data: JSON.stringify({
                    tableData: tableData,
                  }),
                  suggestedName: `报名活动列表数据.json`,
                },
              },
              'https://seller.kuajingmaihuo.com/',
            );
          }}
          size="sm"
          className="mr-3 ml-auto"
        >
          导出列表
        </Button>
        <Button
          onClick={async () => {
            window.parent.postMessage(
              {
                type: PostMessageType.importCorssOriginData,
              },
              'https://seller.kuajingmaihuo.com/',
            );

            window.addEventListener(
              'message',
              async (message: MessageEvent<SendCorssOriginDataMessage>) => {
                if (message.data.type === PostMessageType.sendCorssOriginData) {
                  const dataString = message.data.data.data;
                  // console.log(dataString);
                  try {
                    const tableData = JSON.parse(dataString).tableData;
                    if (!tableData) {
                      throw new Error('是否导入错数据信息');
                    }
                    setTableData(tableData);
                    toast.success(`成功导入配置`);
                  } catch (error) {
                    toast.error(`导入配置失败 ${(error as Error).message}`);
                  }
                }
              },
              {
                once: true,
              },
            );
          }}
          size="sm"
          className=""
        >
          导入列表
        </Button>
      </div>

      <div className="grow relative flex flex-col">
        <div className="mt-2 flex items-center">
          <Button
            onClick={async () => {
              try {
                await fetchTemuProductAndActivityInfo({
                  isSavePreprocessTableData: true,
                });
                // 持久化一下数据
                persistedMallTableData();
                toast.success('获取商品和活动建议信息成功');
              } catch (error) {
                toast.error((error as Error).message);
              }
            }}
            size="sm"
            className="primary-color mr-3"
          >
            获取商品和活动建议信息
          </Button>
          <Button
            disabled={preprocessTableData.length === 0 ? true : false}
            onClick={async () => {
              await regidtrationActivity();
              // 持久化一下数据
              persistedMallTableData();
              toast.success('报名活动任务完成');
            }}
            size="sm"
            className="primary-color mr-3"
          >
            报名活动
          </Button>
          <Button
            onClick={async () => {
              try {
                await fetchAndRegidtrationActivity();
                // 持久化一下数据
                persistedMallTableData();
                toast.success('报名活动任务完成');
              } catch (error) {
                toast.error((error as Error).message);
              }
            }}
            size="sm"
            className="primary-color"
          >
            获取并报名
          </Button>
          <span className="ml-3">
            {isRunning ? '(获取商品总数中...)' : ''}
            {
              skcTopStatusList.find((skcTopStatus) => skcTopStatus.status === storedValue.status)
                ?.label
            }
            : {currentTotal} 个商品
          </span>
          <div className="flex px-3 gap-2 items-center py-4">
            <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
            <Input
              placeholder="货号/SPU/SKC/SKU/结果"
              value={filterString}
              onChange={(event) => {
                setFilterString(event.target.value);
              }}
              className={cn(
                'flex h-10 w-full bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50 rounded-md border border-input',
                className,
              )}
              {...props}
            />
          </div>
          <Button
            onClick={async () => {
              try {
                persistedMallTableData();
                toast.success('列表数据保存成功');
              } catch (error) {
                toast.error((error as Error).message);
              }
            }}
            size="sm"
            className="ml-auto mr-3"
          >
            保存列表
          </Button>
          <Button
            onClick={async () => {
              setTableData([]);
              setPreprocessTableData([]);
              clearMallTableData();
              toast.success('清空保存数据成功');
            }}
            variant={'destructive'}
            size="sm"
            className="mr-3"
          >
            清空保存数据
          </Button>
          <Button
            onClick={async () => {
              await clearTableData();
            }}
            variant={'destructive'}
            size="sm"
            className=""
          >
            清空列表
          </Button>
        </div>
        <TemuProductTable
          mallId={storedValue.mallId}
          data={deferredTableData}
          runBatchTask={runBatchTask}
          activityList={activityList}
        ></TemuProductTable>
        <div className="mt-auto">
          <RegidtrationActivityOperation></RegidtrationActivityOperation>
          {/* <RegidtrationActivityResume
            resumeInfo={(resumeInfoData) => {
              const currentTotal = resumeInfoData.currentTotal;
              const tableData = resumeInfoData.tableData;
              setTableData(tableData || []);
              setCurrentTotal(currentTotal || 0);
            }}
            tableData={tableData}
            currentTotal={currentTotal}
            runBatchTask={runBatchTask}
          ></RegidtrationActivityResume> */}
        </div>
      </div>
    </div>
  );
}

export interface PageParams {
  pageSize: number;
}

const TemuProductTable = memo(function TemuProductTable({
  data,
  runBatchTask,
  mallId,
  activityList,
}: {
  data: RegidtrationActivityTableDataItem[];
  runBatchTask: (
    preprocessTableData: RegidtrationActivityTableDataItem[],
    isEnterQueue?: boolean,
  ) => Promise<void>;
  mallId: number;
  activityList: Activity[];
}) {
  const localStorageKey = config.temu.temuRegidtrationActivityTableKey;
  const id = useId();
  const [columnPinning, setColumnPinning] = useState<ColumnPinningState>({
    left: ['select', 'skuInfo', 'finalActivityPrice', 'finalActivityStock'],
    right: ['opeartionResult', 'actions'],
  });
  const [storedValue, setStoredValue] = useLocalStorage<PageParams>(localStorageKey, {
    pageSize: 10,
  });

  const [pagination, setPagination] = useState<PaginationState>({
    pageIndex: 0,
    pageSize: storedValue.pageSize,
  });
  const [rowSelection, setRowSelection] = useState({});
  const [sorting, setSorting] = useState<SortingState>([]);
  const headerHeight = 60;
  const cellHeight = 50;

  const columns: ColumnDef<RegidtrationActivityTableDataItem>[] = useMemo(() => {
    const columns: ColumnDef<RegidtrationActivityTableDataItem>[] = [];
    columns.push({
      id: 'select',
      header: ({ table }) => (
        <Checkbox
          checked={
            table.getIsAllPageRowsSelected() ||
            (table.getIsSomePageRowsSelected() && 'indeterminate')
          }
          onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
          aria-label="Select all"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(value) => row.toggleSelected(!!value)}
          aria-label="Select row"
        />
      ),
      enableSorting: false,
      enableHiding: false,
    });
    columns.push({
      id: 'skuInfo',
      accessorKey: 'skuInfo',
      header: () => <div className="text-center whitespace-nowrap">sku货号</div>,
      cell: ({ row }) => {
        // console.log(row);
        const skuInfo: string = row.getValue('skuInfo');
        return (
          <div
            onClick={() => {
              gotoGigaProductPage(skuInfo);
            }}
            className="text-left whitespace-nowrap cursor-pointer text-blue-600 underline"
          >
            {skuInfo}
          </div>
        );
      },
    });
    columns.push({
      id: 'finalActivityPrice',
      accessorKey: 'finalActivityPrice',
      header: () => <div className="text-center whitespace-nowrap">最终上报价格</div>,
      cell: ({ row }) => {
        const finalActivityPrice: number = row.getValue('finalActivityPrice');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(finalActivityPrice) ? 'NaN' : +finalActivityPrice / 100}
          </div>
        );
      },
    });

    columns.push({
      id: 'finalActivityStock',
      accessorKey: 'finalActivityStock',
      header: () => <div className="text-center whitespace-nowrap">最终上报库存</div>,
      cell: ({ row }) => {
        const finalActivityStock: number = row.getValue('finalActivityStock');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(finalActivityStock) ? 'NaN' : finalActivityStock}
          </div>
        );
      },
    });

    columns.push({
      id: 'productId',
      accessorKey: 'productId',
      header: () => <div className="text-center whitespace-nowrap">SPUID</div>,
      cell: ({ row }) => {
        const productId: number = row.getValue('productId');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(productId) ? 'NaN' : productId}
          </div>
        );
      },
    });

    columns.push({
      id: 'activityIdentify',
      accessorKey: 'activityIdentify',
      header: () => <div className="text-center whitespace-nowrap">活动</div>,
      cell: ({ row }) => {
        // console.log(row);
        const activityIdentify: string = row.getValue('activityIdentify');
        const activity = activityList.find(
          (item) => generateActivityIdentify(item) === activityIdentify,
        );
        if (activity) {
          let content = generateActivityText(activity);
          return (
            <div
              onClick={() => {
                goToActivityPage(activity);
              }}
              title={content}
              className="max-w-[100px] text-left whitespace-nowrap cursor-pointer text-blue-600 underline text-ellipsis overflow-hidden"
            >
              {content}
            </div>
          );
        } else {
          return <div></div>;
        }
      },
    });

    columns.push({
      id: 'activityMargin',
      accessorKey: 'activityMargin',
      header: () => <div className="text-center whitespace-nowrap">活动利润</div>,
      cell: ({ row }) => {
        const activityMargin: number = row.getValue('activityMargin');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(activityMargin) ? 'NaN' : +activityMargin / 100}
          </div>
        );
      },
    });

    columns.push({
      id: 'activityRateOfMargin',
      accessorKey: 'activityRateOfMargin',
      header: () => <div className="text-center whitespace-nowrap">活动毛利率(%)</div>,
      cell: ({ row }) => {
        const activityRateOfMargin: number = row.getValue('activityRateOfMargin');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(activityRateOfMargin) ? 'NaN' : (+activityRateOfMargin).toFixed(2)}
          </div>
        );
      },
    });

    columns.push({
      id: 'suggestActivityPrice',
      accessorKey: 'suggestActivityPrice',
      header: () => <div className="text-center whitespace-nowrap">活动建议价格</div>,
      cell: ({ row }) => {
        const suggestActivityPrice: number = row.getValue('suggestActivityPrice');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(suggestActivityPrice) ? 'NaN' : +suggestActivityPrice / 100}
          </div>
        );
      },
    });

    columns.push({
      id: 'suggestActivityStock',
      accessorKey: 'suggestActivityStock',
      header: () => <div className="text-center whitespace-nowrap">活动建议库存</div>,
      cell: ({ row }) => {
        const suggestActivityStock: number = row.getValue('suggestActivityStock');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(suggestActivityStock) ? 'NaN' : suggestActivityStock}
          </div>
        );
      },
    });

    columns.push({
      id: 'temuPrice',
      accessorKey: 'temuPrice',
      header: () => <div className="text-center whitespace-nowrap">temu价格</div>,
      cell: ({ row }) => {
        const temuPrice: number = row.getValue('temuPrice');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(temuPrice) ? 'NaN' : +temuPrice / 100}
          </div>
        );
      },
    });

    columns.push({
      id: 'temuStock',
      accessorKey: 'temuStock',
      header: () => <div className="text-center whitespace-nowrap">temu库存</div>,
      cell: ({ row }) => {
        const temuStock: number = row.getValue('temuStock');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(temuStock) ? 'NaN' : temuStock}
          </div>
        );
      },
    });

    columns.push({
      id: 'gigaPrice',
      accessorKey: 'gigaPrice',
      header: () => <div className="text-center whitespace-nowrap">giga价格</div>,
      cell: ({ row }) => {
        const gigaPrice: number = row.getValue('gigaPrice');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(gigaPrice) ? 'NaN' : +gigaPrice / 100}
          </div>
        );
      },
    });

    columns.push({
      id: 'gigaAvaliable',
      accessorKey: 'gigaAvaliable',
      header: () => <div className="text-center whitespace-nowrap">giga库存</div>,
      cell: ({ row }) => {
        const gigaAvaliable: number = row.getValue('gigaAvaliable');
        return (
          <div className="text-left whitespace-nowrap">
            {Number.isNaN(gigaAvaliable) ? 'NaN' : gigaAvaliable}
          </div>
        );
      },
    });
    // opeartionResult: string;
    columns.push({
      id: 'skcId',
      accessorKey: 'skcId',
      header: () => <div className="text-center whitespace-nowrap">SKCID</div>,
      cell: ({ row }) => {
        const skcId: number = row.getValue('skcId');
        return (
          <div className="text-left whitespace-nowrap">{Number.isNaN(skcId) ? 'NaN' : skcId}</div>
        );
      },
    });
    columns.push({
      id: 'skcInfo',
      accessorKey: 'skcInfo',
      header: () => <div className="text-center whitespace-nowrap">skc货号</div>,
      cell: ({ row }) => {
        const skcInfo: string = row.getValue('skcInfo');
        return <div className="text-left whitespace-nowrap">{skcInfo}</div>;
      },
    });
    columns.push({
      id: 'skuId',
      accessorKey: 'skuId',
      header: () => <div className="text-center whitespace-nowrap">skuId</div>,
      cell: ({ row }) => {
        const skuId: string = row.getValue('skuId');
        return (
          <div className="text-left whitespace-nowrap">{Number.isNaN(skuId) ? 'NaN' : skuId}</div>
        );
      },
    });
    columns.push({
      id: 'mallId',
      accessorKey: 'mallId',
      header: () => <div className="text-center whitespace-nowrap">店铺ID</div>,
      cell: ({ row }) => {
        const mallId: number = row.getValue('mallId');
        return (
          <div className="text-left whitespace-nowrap">{Number.isNaN(mallId) ? 'NaN' : mallId}</div>
        );
      },
    });
    columns.push({
      id: 'timeStamp',
      accessorKey: 'timeStamp',
      header: () => <div className="text-center whitespace-nowrap">处理时间</div>,
      cell: ({ row }) => {
        const timeStamp: number = row.getValue('timeStamp');
        return (
          <div className="text-left whitespace-nowrap">{new Date(timeStamp).toLocaleString()}</div>
        );
      },
    });
    columns.push({
      id: 'opeartionResult',
      accessorKey: 'opeartionResult',
      header: () => <div className="text-center whitespace-nowrap">操作结果</div>,
      cell: ({ row }) => {
        const opeartionResult: string = row.getValue('opeartionResult');
        return (
          <div
            title={opeartionResult}
            className={`text-left max-w-20 whitespace-nowrap overflow-hidden text-ellipsis`}
            style={{
              color: getOperationResultColor(opeartionResult),
            }}
          >
            {opeartionResult}
          </div>
        );
      },
    });

    columns.push({
      id: 'actions',
      enableHiding: false,
      enableSorting: false,
      header() {
        return <div className="text-center">操作</div>;
      },
      cell: ({ row }) => {
        return (
          <div>
            <Button
              onClick={async () => {
                const productId: number = row.getValue('productId');
                const original = row.original;
                toast.promise(runBatchTask([original], false), {
                  loading: `[${productId}] 正在报名活动...`,
                  success: (result) => {
                    return `[${productId}] 完成报名活动`;
                  },
                  error: (error) => {
                    return `[${productId}] 报名活动失败: ${(error as Error).message}`;
                  },
                });
              }}
              size="sm"
              className="hover:bg-[#337AB7] bg-[#428BCA]"
            >
              报名活动
            </Button>
          </div>
        );
      },
    });
    return columns;
  }, [runBatchTask, activityList]);

  const table = useReactTable({
    data,
    columns,
    onColumnPinningChange: setColumnPinning,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    onPaginationChange: setPagination,
    onRowSelectionChange: setRowSelection,
    onSortingChange: setSorting,
    state: {
      rowSelection,
      columnPinning,
      pagination,
      sorting,
    },
  });

  return (
    data.length > 0 && (
      <div className="w-full grow relative flex flex-col mt-2">
        <div className="grow relative">
          <div className="rounded-sm !absolute h-full w-full overflow-auto">
            <div className="rounded-md border min-w-full inline-flex [&_thead]:sticky [&_thead]:top-[1px] [&_thead]:[box-shadow:0px_0px_0px_1px_#cfcfcf] [&_thead]:bg-[#f5f5f5]  [&_table]:!overflow-visible">
              <div className="sticky left-[0px] z-10 bg-white">
                <Table className="[&_td]:border [&_td]:border-input [&_th]:border [&_th]:border-input text-xs">
                  <TableHeader>
                    {table.getLeftHeaderGroups().map((headerGroup) => (
                      <TableRow key={headerGroup.id}>
                        {headerGroup.headers.map((header) => {
                          return (
                            <TableHead
                              key={header.id}
                              className="!p-2 relative"
                              style={{
                                height: headerHeight,
                              }}
                            >
                              {header.column.getCanSort() ? (
                                <div
                                  onClick={header.column.getToggleSortingHandler()}
                                  className="absolute cursor-pointer right-1 bottom-1"
                                  title={
                                    header.column.getCanSort()
                                      ? header.column.getNextSortingOrder() === 'asc'
                                        ? '升序'
                                        : header.column.getNextSortingOrder() === 'desc'
                                          ? '降序'
                                          : '默认排序'
                                      : undefined
                                  }
                                >
                                  <ArrowUpDown size={12}></ArrowUpDown>
                                </div>
                              ) : null}
                              {header.isPlaceholder
                                ? null
                                : flexRender(header.column.columnDef.header, header.getContext())}
                            </TableHead>
                          );
                        })}
                      </TableRow>
                    ))}
                  </TableHeader>
                  <TableBody>
                    {table.getRowModel().rows?.length ? (
                      table.getRowModel().rows?.map((row) => {
                        return (
                          <TableRow key={row.id} data-state={row.getIsSelected() && 'selected'}>
                            {row.getLeftVisibleCells().map((cell) => (
                              <TableCell
                                key={cell.id}
                                className=""
                                style={{
                                  height: cellHeight,
                                }}
                              >
                                {flexRender(cell.column.columnDef.cell, cell.getContext())}
                              </TableCell>
                            ))}
                          </TableRow>
                        );
                      })
                    ) : (
                      <TableRow>
                        <TableCell colSpan={columns.length} className="h-24 text-center">
                          No results.
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
              <div className="relative grow">
                <Table className="text-xs [&_td]:border [&_td]:border-input [&_th]:border [&_th]:border-input">
                  <TableHeader>
                    {table.getCenterHeaderGroups().map((headerGroup) => (
                      <TableRow key={headerGroup.id}>
                        {headerGroup.headers.map((header) => {
                          return (
                            <TableHead
                              key={header.id}
                              className="!p-2 relative"
                              style={{
                                height: headerHeight,
                              }}
                            >
                              {header.column.getCanSort() ? (
                                <div
                                  onClick={header.column.getToggleSortingHandler()}
                                  className="absolute cursor-pointer right-1 bottom-1"
                                  title={
                                    header.column.getCanSort()
                                      ? header.column.getNextSortingOrder() === 'asc'
                                        ? '升序'
                                        : header.column.getNextSortingOrder() === 'desc'
                                          ? '降序'
                                          : '默认排序'
                                      : undefined
                                  }
                                >
                                  <ArrowUpDown size={12}></ArrowUpDown>
                                </div>
                              ) : null}
                              <div className="text-xs">
                                {header.isPlaceholder
                                  ? null
                                  : flexRender(header.column.columnDef.header, header.getContext())}
                              </div>
                            </TableHead>
                          );
                        })}
                      </TableRow>
                    ))}
                  </TableHeader>
                  <TableBody>
                    {table.getRowModel().rows?.length ? (
                      table.getRowModel().rows.map((row) => (
                        <TableRow key={row.id} data-state={row.getIsSelected() && 'selected'}>
                          {row.getCenterVisibleCells().map((cell) => (
                            <TableCell
                              key={cell.id}
                              className=""
                              style={{
                                height: cellHeight + 'px',
                              }}
                            >
                              {flexRender(cell.column.columnDef.cell, cell.getContext())}
                            </TableCell>
                          ))}
                        </TableRow>
                      ))
                    ) : (
                      <TableRow>
                        <TableCell colSpan={columns.length} className="h-24 text-center">
                          No results.
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
              <div className="bg-white sticky right-0">
                <Table className="text-xs [&_td]:border [&_td]:border-input [&_th]:border [&_th]:border-input">
                  <TableHeader>
                    {table.getRightHeaderGroups().map((headerGroup) => (
                      <TableRow key={headerGroup.id}>
                        {headerGroup.headers.map((header) => {
                          return (
                            <TableHead
                              key={header.id}
                              className="!p-2 relative"
                              style={{
                                height: headerHeight,
                              }}
                            >
                              {header.column.getCanSort() ? (
                                <div
                                  onClick={header.column.getToggleSortingHandler()}
                                  className="absolute cursor-pointer right-1 bottom-1"
                                  title={
                                    header.column.getCanSort()
                                      ? header.column.getNextSortingOrder() === 'asc'
                                        ? '升序'
                                        : header.column.getNextSortingOrder() === 'desc'
                                          ? '降序'
                                          : '默认排序'
                                      : undefined
                                  }
                                >
                                  <ArrowUpDown size={12}></ArrowUpDown>
                                </div>
                              ) : null}
                              {header.isPlaceholder
                                ? null
                                : flexRender(header.column.columnDef.header, header.getContext())}
                            </TableHead>
                          );
                        })}
                      </TableRow>
                    ))}
                  </TableHeader>
                  <TableBody>
                    {table.getRowModel().rows?.length ? (
                      table.getRowModel().rows.map((row) => (
                        <TableRow key={row.id} data-state={row.getIsSelected() && 'selected'}>
                          {row.getRightVisibleCells().map((cell) => (
                            <TableCell
                              key={cell.id}
                              className=""
                              style={{
                                height: cellHeight + 'px',
                              }}
                            >
                              {flexRender(cell.column.columnDef.cell, cell.getContext())}
                            </TableCell>
                          ))}
                        </TableRow>
                      ))
                    ) : (
                      <TableRow>
                        <TableCell colSpan={columns.length} className="h-24 text-center">
                          No results.
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </div>
          </div>
        </div>
        <div className="mt-1 relative">
          <div className="absolute">
            <Button
              onClick={async () => {
                if (table.getIsSomeRowsSelected() || table.getIsAllRowsSelected()) {
                  const originals = table.getSelectedRowModel().rows.map((row) => {
                    return row.original;
                  });
                  toast.promise(runBatchTask(originals, false), {
                    loading: '正在批量报名活动...',
                    success: (result) => {
                      return `批量报名活动成功`;
                    },
                    error: (error) => {
                      return `批量报名活动失败: ${(error as Error).message}`;
                    },
                  });
                }
              }}
              size="sm"
              className="hover:bg-[#337AB7] bg-[#428BCA] mr-3 mt-5"
            >
              批量报名活动
            </Button>
          </div>
          <TablePagination<RegidtrationActivityTableDataItem, PageParams>
            setStoredValue={setStoredValue}
            storedValue={storedValue}
            table={table}
            setPagination={setPagination}
          ></TablePagination>
        </div>
      </div>
    )
  );
});
